package edu.hawaii.duedates.lender;

import java.util.ArrayList;
import java.util.List;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import edu.hawaii.duedates.ItemDue;

/**
 * A class for the Hawaii State Library system that implements LibraryVault. 
 * Stores information about URL and login form data. Implements methods for logging 
 * in and returning data from the library.
 * 
 * @author Tyler Wolff and Scheller Sanchez
 */
public class HawaiiStateLibrary implements Lender {
  private static final String name = "Hawaii State Public Library";

  /* URL for the Hawaii State library system */
  private static final String libUrl = "http://www.librarieshawaii.org/";
  
  // Form information for the System
  private static final String param1 = "sec1";
  private static final String param2 = "sec2";
  
  /**
   * Attempts to login to a given Library system with user information. System makes use of an
   * HttpUnit WebConversation to scan a systems web page for login form, then inputs user
   * information and submits. Returns a null WebConversation if login was unsuccessful.
   * 
   * @param id The user ID or first login parameter.
   * @param pass The user password or second login parameter.
   * @return The WebConversation instance after successful login.
   * @throws Exception If login was not successful with these credentials.
   */
  public WebConversation login (String id, String pass) throws Exception {

    // If website has bogus JavaScript code, do not throw error.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(libUrl);
    WebResponse response = conversation.getResponse(request);
    
    WebLink link = response.getLinkWith("My Account");
    link.click();
    response = conversation.getCurrentPage();
    WebForm form = response.getForms()[0];
    form.setParameter(param1, id);
    form.setParameter(param2, pass);
    form.submit(); 
    response = conversation.getCurrentPage();
      
    // Return null conversation if Login unsuccessful
    if (response.getText().contains("Login failed")) {
      conversation = null;
      System.out.println("-- Login to the Hawaii State Library was unsuccessful --");
    }

    return conversation;

  }
  
  /**
   * Utilizes a users information to login to a given library system and gather data 
   * about the users current check out books. Returns a list of itemDue Objects.
   * 
   * @param param1 First user parameter for logging in.
   * @param param2 Second user parameter for logging in.
   * @return A list of ItemDue Objects.
   * @throws Exception if login was unsuccessful.
   */
  public List<ItemDue> getItemInfo (String param1, String param2) throws Exception {
    
      List<ItemDue> itemsDue = new ArrayList<ItemDue>();
      
    try {

      WebConversation conversation = this.login(param1, param2);
      
      // If login was unsuccessful
      if (conversation == null) {
        return itemsDue;
      }
      
      WebResponse response = conversation.getCurrentPage();
      WebLink link = response.getLinkWith("Items Out");
      link.click();
      response = conversation.getCurrentPage();
      boolean noBooksOut = response.getText().contains("Checked Out: 0");

      // whiteSpace created to account for all sized book descriptions
      String whiteSpace = "                                                  ";          
        
      
      if (!noBooksOut) {
        WebTable table = response.getTableStartingWith("Title");
        
        for (int i = 1; i < table.getRowCount(); i++) {
          
          // formatting the title of book (removing new line char)
          String [] tempTitle = table.getCellAsText(i, 0).split("\n", 2);
          String Title = tempTitle[0].substring(2);
          Title = Title.concat(tempTitle[1]).concat(whiteSpace);
          
          // formatting due date to be mm-dd-yy
          String dueDate = table.getCellAsText(i, 2);
          String dueDateFormatted = dueDate.substring(0, 2) + "-" + dueDate.substring(3, 5)
              + "-" + dueDate.substring(8);
          
          ItemDue tempItem = new ItemDue("Hawaii State Library", Title, "n/a", 
              dueDateFormatted);
          itemsDue.add(tempItem);
        }
      }
      
      return itemsDue;
    }
    catch (Exception e) {
      throw new Exception(e.getMessage(), e);
    }
    
  }

  /**
   * Gets library name.
   * 
   * @return Library name.
   */
  public String getLenderName() {
    return name;
  }

}
